"""
Author: Meng
Date: 2018/8/22
"""
from functools import wraps
from f_lib.code import Msg
from flask import request
from app.models.safety.request_log import RequestLog
from settings import MAX_REQUEST_HOUR
from datetime import datetime
import json


def safety_strategy(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        headers = request.headers
        req_ip = headers.get('X-Real-Ip') if headers.get('X-Real-Ip') else headers.get('X-Forwarded') or '127.0.0.1'
        agent = headers.get('User-Agent')
        path = request.path
        get_arg = json.dumps(dict(request.args))
        method = request.method
        post_arg = json.dumps(request.json)
        url = request.url
        username = request.cookies.get('username')
        logs_count = RequestLog.query_count(ip=req_ip, time=datetime.now().strftime('%Y-%m-%d %H'))
        if logs_count > MAX_REQUEST_HOUR:
            return Msg.failed_dict(402)
        RequestLog.create(ip=req_ip,
                          path=path,
                          agent=agent,
                          get_args=get_arg,
                          method=method,
                          post_args=post_arg,
                          url=url,
                          username=username
                          )

        return func(*args, **kwargs)

    return decorated_view


def component_safety_strategy():
    headers = request.headers
    req_ip = headers.get('X-Real-Ip') if headers.get('X-Real-Ip') else headers.get('X-Forwarded') or '127.0.0.1'
    agent = headers.get('User-Agent')
    path = request.path
    get_arg = json.dumps(dict(request.args))
    method = request.method
    post_arg = json.dumps(request.json)
    url = request.url
    username = request.cookies.get('username')
    logs_count = RequestLog.query_count(ip=req_ip, time=datetime.now().strftime('%Y-%m-%d %H'))
    if logs_count > MAX_REQUEST_HOUR:
        return Msg.failed_dict(402)
    RequestLog.create(ip=req_ip,
                      path=path,
                      agent=agent,
                      get_args=get_arg,
                      method=method,
                      post_args=post_arg,
                      url=url,
                      username=username
                      )
